// Content script to capture XHR requests and save search data
(function() {
  console.log("Xiaohongshu Search Export Tool initialized in isolated context");
  
  // 注入外部脚本而不是内联脚本，避免CSP错误
  const injectInterceptScript = () => {
    const script = document.createElement('script');
    script.src = chrome.runtime.getURL('xhr-interceptor.js');
    script.onload = function() {
      // 脚本加载后可以移除，以保持清洁
      this.remove();
    };
    (document.head || document.documentElement).appendChild(script);
    console.log("Intercept script injected");
  };
  
  // 在页面加载完成后注入拦截脚本
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', injectInterceptScript);
  } else {
    injectInterceptScript();
  }
  
  // 监听从页面脚本发来的消息
  window.addEventListener("message", function(event) {
    // 确保消息来自我们期望的源
    if (event.source !== window) return;
    
    const message = event.data;
    
    // 处理搜索数据
    if (message && message.type === "XIAOHONGSHU_SEARCH_DATA") {
      try {
        const { query, responseData, url, timestamp } = message;
        console.log("Received search data:", query, responseData, url, timestamp);
        
        const data = responseData.data.items;
        const items = [];
        
        if (data && Array.isArray(data)) {
          data.forEach(item => {
            if (item && item.model_type === "note" && item.note_card) {
              try {
                const newItem = {
                  id: item.id,
                  query: query,
                  user: item.note_card.user,
                  title: item.note_card.display_title,
                  image: item.note_card.cover ? item.note_card.cover.url_default : null,
                  image_list: item.note_card.image_list || [],
                  corner_tag_info: item.note_card.corner_tag_info || [],
                  type: item.note_card.type,
                  timestamp: timestamp,
                  url: url
                };
                items.push(newItem);
              } catch (itemError) {
                console.error("Error processing item:", itemError);
              }
            }
          });
          
          // 发送数据到background script存储
          if (items.length > 0) {
            chrome.runtime.sendMessage({
              action: "saveSearchData",
              query: query,
              items: items,
              timestamp: timestamp,
              url: url
            });
            console.log("Data sent to background script");
          }
        }
      } catch (e) {
        console.error("Error processing message:", e);
      }
    }
  });
})();
